<template>
  <div>
    <el-form :model="form" :rules="formRules" ref="formRef" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="文章标题" prop="title">
            <el-input id="title" v-model="form.title" placeholder="请输入标题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文章首图URL" prop="firstPicture">
            <el-input id="firstPicture" v-model="form.firstPicture" placeholder="文章首图，用于随机文章展示"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="文章描述" prop="description">
        <mavon-editor
          ref="content"
          v-model="form.description"
          :toolbars="toolbars"
          @imgAdd="imgAddDescription"
        />
      </el-form-item>

      <el-form-item label="文章正文" prop="content">
        <mavon-editor ref="content" v-model="form.content" @imgAdd="imgAdd" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="categoryName">
            <el-select
              id="categoryName"
              v-model="form.categoryName"
              placeholder="请选择分类（输入可添加新分类）"
              :allow-create="true"
              :filterable="true"
              style="width: 100%"
            >
              <el-option
                :label="item.categoryName"
                :value="item.categoryName"
                v-for="item in categoryList"
                :key="item.categoryName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签" prop="tagList">
            <el-select
              id="tagList"
              v-model="form.tagList"
              placeholder="请选择标签（输入可添加新标签）"
              :allow-create="true"
              :filterable="true"
              :multiple="true"
              style="width: 100%"
            >
              <el-option
                :label="item.tagName"
                :value="item.tagName"
                v-for="item in tagList"
                :key="item.tagName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="字数" prop="words">
            <el-input id="words" v-model="form.words" placeholder="请输入文章字数（自动计算阅读时长）" type="number"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="阅读时长(分钟)" prop="readTime">
            <el-input
              id="readTime"
              v-model="form.readTime"
              placeholder="请输入阅读时长（可选）默认 Math.round(字数 / 200)"
              type="number"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="浏览次数" prop="views">
            <el-input id="views" v-model="form.views" placeholder="请输入文章字数（可选）默认为 0" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item style="text-align: right">
        <el-button type="primary" @click="dialogVisible = true">保存</el-button>
      </el-form-item>
    </el-form>

    <!--编辑可见性状态对话框-->
    <el-dialog title="博客可见性" width="30%" :visible.sync="dialogVisible">
      <!--内容主体-->
      <el-form label-width="50px" @submit.native.prevent>
        <el-form-item>
          <el-radio-group v-model="form.showPermission">
            <el-radio :label="1">公开</el-radio>
            <el-radio :label="2">私密</el-radio>
            <el-radio :label="3">密码保护</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" v-if="form.showPermission === 3">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item v-if="form.showPermission !== 2">
          <el-row>
            <el-col :span="6">
              <el-switch
                v-model="form.isAppreciation"
                :active-value="1"
                :inactive-value="0"
                active-text="赞赏"
              ></el-switch>
            </el-col>
            <el-col :span="6">
              <el-switch
                v-model="form.isRecommend"
                :active-value="1"
                :inactive-value="0"
                active-text="推荐"
              ></el-switch>
            </el-col>
            <el-col :span="6">
              <el-switch
                v-model="form.isCommentEnabled"
                :active-value="1"
                :inactive-value="0"
                active-text="评论"
              ></el-switch>
            </el-col>
            <el-col :span="6">
              <el-switch
                v-model="form.isTop"
                :active-value="1"
                :inactive-value="0"
                active-text="置顶"
              ></el-switch>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <!--底部-->
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'
import { findBlogRelatedData, create, update, findById } from '@/api/blog'
import { upload } from '@/api/oss'

export default {
  name: 'WriteBlog',
  components: { Breadcrumb },
  data () {
    return {
      categoryList: [],
      tagList: [],
      dialogVisible: false,

      form: {
        title: '',
        firstPicture: '',
        description: '',
        content: '',
        categoryName: null,
        tagList: [],
        words: null,
        readTime: null,
        views: 0,
        isAppreciation: 1,
        isRecommend: 1,
        isCommentEnabled: 1,
        isTop: 0,
        showPermission: 1,
        password: ''
      },
      formRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'change' }],
        firstPicture: [
          { required: true, message: '请输入首图链接', trigger: 'change' }
        ],
        categoryName: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        tagList: [{ required: true, message: '请选择标签', trigger: 'change' }],
        words: [
          { required: true, message: '请输入文章字数', trigger: 'change' }
        ]
      },
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        navigation: true, // 导航目录
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        subfield: true, // 单双栏模式
        preview: true // 预览
      }
    }
  },
  watch: {
    'form.words' (newValue) {
      this.form.readTime = newValue ? Math.round(newValue / 200) : null
    }
  },
  created () {
    this.getData()
    if (this.$route.params.id) {
      this.getBlog(this.$route.params.id)
    }
  },
  methods: {
    imgAdd (pos, $file) {
      var formdata = new FormData()
      formdata.append("file", $file)
      upload(formdata).then(res => {
        this.$refs.content.$img2Url(pos, res.data)
      })
    },
    imgAddDescription (pos, $file) {
      var formdata = new FormData()
      formdata.append("file", $file)
      upload(formdata).then(res => {
        this.$refs.description.$img2Url(pos, res.data)
      })
    },

    getData () {
      findBlogRelatedData().then(res => {
        this.categoryList = res.data.categoryList
        this.tagList = res.data.tagList
      })
    },
    getBlog (id) {
      findById(id).then(res => {
        this.form = res.data
        const tagList = res.data.tagList
        let tags = []
        tagList.forEach(e => {
          tags.push(e.tagName)
        })
        this.form.tagList = tags
      })
    },
    submit () {
      if (this.form.showPermission === 3 && !this.form.password) {
        return this.msgError('密码保护模式必须填写密码！')
      }
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.form.showPermission === 3) {
            if (!this.form.password) {
              return this.msgError('密码保护模式必须填写密码！')
            }
          } else {
            this.form.password = ''
            if (this.form.showPermission === 2) {
              this.form.isAppreciation = 0
              this.form.isRecommend = 0
              this.form.isCommentEnabled = 0
              this.form.isTop = 0
            }
          }
          if (this.$route.params.id) {
            update(this.form).then(res => {
              this.msgSuccess(res.msg)
              this.$router.push('/blog/list')
            })
          } else {
            create(this.form).then(res => {
              this.msgSuccess(res.msg)
              this.$router.push('/blog/list')
            })
          }
        } else {
          this.dialogVisible = false
          return this.msgError('请填写必要的表单项')
        }
      })
    }
  }
}
</script>

<style scoped></style>
